import shutil
from pathlib import Path
import logging
from dotenv import load_dotenv
import subprocess
import os
import uuid

load_dotenv()
api_path = os.getenv("API_BASE_URL", "http://localhost")
BACKEND_PORT= os.getenv("BACKEND_PORT", 8483)

BACKEND_BASE_URL = f"{api_path}:{BACKEND_PORT}"

logger = logging.getLogger(__name__)

from typing import Optional
def generate_screenshot(video_path: str, output_dir: str, timestamp: int, index: int) -> str:
    """
    使用 ffmpeg 生成截图，返回生成图片路径
    
    :param video_path: 视频文件路径
    :param output_dir: 输出目录
    :param timestamp: 视频时间戳（秒）
    :param index: 截图序号
    :return: 生成的图片路径
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # 格式化时间戳为mm:ss格式
    minutes = timestamp // 60
    seconds = timestamp % 60
    time_str = f"{minutes:02d}:{seconds:02d}"
    
    # 生成文件名：timestamp_index_uuid.jpg
    filename = f"{time_str}_{index:03d}_{uuid.uuid4()}.jpg"
    output_path = output_dir / filename

    command = [
        "ffmpeg",
        "-ss", str(timestamp),
        "-i", str(video_path),
        "-frames:v", "1",
        "-q:v", "2",  # 质量设置，2是较好的质量
        "-vf", "scale='min(1280,iw)':'-1'",  # 限制最大宽度为1280，保持宽高比
        str(output_path),
        "-y"
    ]

    logger.info(f"生成截图，时间戳：{time_str}，输出路径：{output_path}")
    result = subprocess.run(command, capture_output=True, text=True)

    if result.returncode != 0:
        logger.error(f"ffmpeg 执行失败: {result.stderr}")
        return ""

    if not output_path.exists():
        logger.error(f"截图文件未生成：{output_path}")
        return ""

    logger.info(f"截图生成成功：{output_path}")
    return str(output_path)



def save_cover_to_static(local_cover_path: str, subfolder: Optional[str] = "cover") -> str:
    """
    将封面图片保存到 static 目录下，并返回前端可访问的路径
    :param local_cover_path: 本地原封面路径（比如提取出来的jpg）
    :param subfolder: 子目录，默认是 cover，可以自定义
    :return: 前端访问路径，例如 /static/cover/xxx.jpg，空路径返回空字符串
    """
    # 如果封面路径为空，直接返回空字符串
    if not local_cover_path:
        return ""

    # 项目根目录
    project_root = os.getcwd()

    # static目录
    static_dir = os.path.join(project_root, "static")

    # 确定目标子目录
    target_dir = os.path.join(static_dir, subfolder or "cover")
    os.makedirs(target_dir, exist_ok=True)

    # 拷贝文件
    file_name = os.path.basename(local_cover_path)
    target_path = os.path.join(target_dir, file_name)
    shutil.copy2(local_cover_path, target_path)  # 保留原时间戳、权限
    image_relative_path = f"/static/{subfolder}/{file_name}".replace("\\", "/")
    url_path = f"{BACKEND_BASE_URL.rstrip('/')}/{image_relative_path.lstrip('/')}"
    # 返回前端可访问的路径
    return url_path
